package com.sky.websocket;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: WebSocketServer
 * Package: com.sky.websocket
 * Description:
 *测试服务websocket
 * @Author 那啥啥
 * @Create 2024/3/20  17:06
 * @Version 1.0
 */
@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {
 //存放会话对象
 private static Map<String, Session> sessionMap = new HashMap();

    /**
     * 链接建立成功调用的方法
     * @param session
     * @param sid
     */
    @OnOpen
 public void onOpen(Session session , @PathParam("sid") String sid){
        log.info("客户端{}建立连接",sid);
     System.out.println("客户端" + sid + "建立连接");
     sessionMap.put(sid,session);
 }

    /**
     * 收到客户发来的消息
     * @param message
     * @param sid
     */
    @OnMessage
    public  void  onMessage(String message ,@PathParam("sid") String sid){
        System.out.println("收到客户端" + sid + "传来的消息" + message);
 }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
